<template>
  <div class="component-upload-image">
    <!-- :class="{ hide: this.fileList.length >= this.limit }" 隐藏上传图片的按钮 -->
    <el-upload
      multiple
      :action="uploadImgUrl"
      :data="{ storageType: storageType }"
      :list-type="listImgType"
      :on-success="
        (res, file) => {
          return handleUploadSuccess(res, file, imgIndex);
        }
      "
      :limit="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      name="file"
      :show-file-list="true"
      :headers="headers"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :on-change="onChange"
      :on-remove="
        (file) => {
          return handleRemove(file, imgIndex);
        }
      "
      :on-preview="handlePictureCardPreview"
    >
      <div class="w_file">
        <div class="w_icon">
          <img class="uploadIcon" src="@/assets/images/upload.png" />
          <p class="uploadText">{{ text }}</p>
        </div>
      </div>
      <div
        slot="file"
        slot-scope="{ file }"
        v-if="listImgType === 'picture-card'"
      >
        <img v-if="loading" class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            class="el-upload-list__item-delete"
            @click="handleRemove(file, imgIndex)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <div class="fileType" slot="tip" v-if="showTip">
      支持类型：<span>{{ fileType.join("、") }}</span>
    </div>
    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      style="height: 70vh"
      append-to-body
    >
      <video
        v-if="isVideo"
        :src="dialogImageUrl"
        controls
        preload
        width="100%"
        height="100%"
      >
        <source :src="dialogImageUrl" />
      </video>
      <img
        v-else
        :src="dialogImageUrl"
        height="100%"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { detailsImg } from "@/api/file/index";
export default {
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 5,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: false,
    },
    text: {
      type: String,
      default: "上传图片",
    },
    // 图片展示类型
    listType: {
      type: String,
      default: "picture",
    },
    // 文件下标
    imgIndex: {
      type: Number,
      default: 1,
    },
    // 存储类型
    storageType: {
      type: String,
      default: 'local'
    }
  },
  data() {
    return {
      number: 0,
      uploadList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      hideUpload: false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/file/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],
      isVideo: false,
      listImgType: "",
      // 图片类型
      imgType: ["jpg", "png", "gif"],
      // 视频类型
      videoType: ["mp4"],
      successImgUrl: null,
      loading: false
    };
  },
  watch: {
    value: {
      handler(val) {
        this.loading = true;
        if (val.length > 0) {
          this.fileList = val;
          if (val.length === 1) {
            const type = val[0].name.split(".")[1];
            if (this.imgType.includes(type)) {
              this.isVideo = false;
              this.listImgType = "picture-card";
            } else {
              this.isVideo = true;
              this.listImgType = "text";
            }
          }
        } else {
          this.fileList = [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  created() {
    this.listImgType = this.listType;
  },
  methods: {
    // 上传前，区分上传的类型
    beforeUpload(file) {
      this.isVideo = false;
      this.loading = false;
      const type = file.name.split(".")[1];
      if (this.imgType.includes(type)) {
        this.listImgType = "picture-card";
        return;
      } else if (this.videoType.includes(type)) {
        this.isVideo = true;
      } else {
        this.isVideo = false;
      }
      this.listImgType = "text";
    },
    onChange(file, fileList) {
      this.fileList = fileList;
    },
    // 删除图片
    handleRemove(file, index) {
      this.fileList.forEach((item, index) => {
        if (item.uid === file.uid) {
          this.fileList.splice(index, 1);
        }
      });
      this.$emit("input", true, file, index);
    },
    // 上传成功回调
    handleUploadSuccess(res, file, index) {
      detailsImg({ fileId: res.data.fileId }).then(response => {
        this.successImgUrl = response.data.url;
        this.loading = true;
      })
      if(Boolean(res.data.fileId) === false) {
        return this.$message.error('文件上传失败！');
      }
      this.$emit("input", res, file, index);
    },

    // 上传前loading加载
    // :before-upload="handleBeforeUpload"
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(
          `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
        );
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传，请稍候...");
      this.number++;
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 预览
    handlePictureCardPreview(file) {
      const type = file.name.split(".")[1];
      if (this.videoType.includes(type) || this.imgType.includes(type)) {
        if (this.videoType.includes(type) && !file.url) {
          detailsImg({
            fileId: file.response.data.fileId,
          }).then((res) => {
            this.dialogImageUrl = res.data.url;
          });
        } else {
          this.dialogImageUrl = file.url;
        }
        this.dialogVisible = true;
      }
    },
  },
};
</script>
<style scoped lang="scss">
// .el-upload--picture-card 控制加号部分
::v-deep.hide .el-upload--picture-card {
  display: none;
}
// 去掉动画效果
::v-deep .el-list-enter-active,
::v-deep .el-list-leave-active {
  transition: all 0s;
}

::v-deep .el-list-enter,
.el-list-leave-active {
  opacity: 0;
  transform: translateY(0);
}
.component-upload-image {
  .w_file {
    display: flex;
    .w_icon {
      width: 130px;
      height: 80px;
      background: #f4f7fa;
      border-radius: 4px;
      border: 1px dashed #416a8c;
      text-align: center;
      cursor: pointer;
      .uploadIcon {
        width: 26px;
        height: 26px;
        vertical-align: middle;
        margin-top: 15px;
      }
      .uploadText {
        font-size: 14px;
        font-family: SourceHanSansCN-Regular, SourceHanSansCN;
        font-weight: 400;
        color: #971111;
        line-height: 32px;
        margin: 0;
      }
    }
    .el-upload-list--picture .el-upload-list__item {
      height: 70px;
      .el-upload-list__item-thumbnail {
        height: 50px;
        width: 50px;
      }
      .el-upload-list__item-name {
        line-height: 50px;
      }
    }
  }
  .fileType {
    font-size: 14px;
    font-family: SourceHanSansCN-Regular, SourceHanSansCN;
    font-weight: 400;
    color: #999999;
    line-height: 52px;
  }
  ::v-deep .el-upload--picture-card {
    width: 130px !important;
    height: 80px !important;
    line-height: 26px;
  }
}
::v-deep .el-dialog {
  width: 800px;
  height: calc(100% - 6vh);
}
::v-deep .el-dialog .el-dialog__body {
  height: calc(100% - 68px);
}
</style>
